import cv2 as cv
import sys
import os
from python_ai.common.xcommon import *
import matplotlib.pyplot as plt
import numpy as np
import time
import datetime

# img_dir = '../../../../../large_data/CV2/lesson/Day07'
# img_name = 'hammer.jpg'
# img_name = 'Moscow.jpeg'
img_dir = '../../../../../large_data/pic'
# img_name = 'DSC05039.JPG'
# img_name = 'DSC05022_1.JPG'
# img_name = 'dog.jpg'
# img_name = 'dog_bird.jpg'
img_name = 'football.jpg'
# img_name = 'messi5.jpg'
# img_dir = '../../../../../large_data/pic/gray'
# img_name = '2008_0719_0019.JPG'
# img_name = 'gray_in_pdf.png'
img_path = os.path.join(img_dir, img_name)

sep('load')
img = cv.imread(img_path, cv.IMREAD_COLOR)
# img = cv.resize(img, None, fx=0.1, fy=0.1, interpolation=cv.INTER_CUBIC)
print('original shape', img.shape)
H, W, CH = img.shape
H2 = H // 2
W2 = W // 2

roi = img[220:320, 10:170]
H_ROI, W_ROI, _ = roi.shape
print_numpy_ndarray_info(roi, 'roi')

# R = I / M
img_hsv = cv.cvtColor(img, cv.COLOR_BGR2HSV)
roi_hsv = cv.cvtColor(roi, cv.COLOR_BGR2HSV)
H_MAX = 180
S_MAX = 256
hist_img = cv.calcHist([img_hsv], [0, 1], None, [H_MAX, S_MAX], [0, H_MAX, 0, S_MAX])
hist_roi = cv.calcHist([roi_hsv], [0, 1], None, [H_MAX, S_MAX], [0, H_MAX, 0, S_MAX])
R = hist_roi / (hist_img + 1e-8)
R_rate = R.copy()
cv.normalize(hist_img, hist_img, 0, 255, cv.NORM_MINMAX)
cv.normalize(hist_roi, hist_roi, 0, 255, cv.NORM_MINMAX)
cv.normalize(R, R, 0, 255, cv.NORM_MINMAX)
hist_img = hist_img.astype(np.uint8)
hist_roi = hist_roi.astype(np.uint8)
R = R.astype(np.uint8)
cv.line(hist_img, (S_MAX-1, 0), (S_MAX-1, H_MAX-1), 255, 1)
cv.line(hist_roi, (S_MAX-1, 0), (S_MAX-1, H_MAX-1), 255, 1)
cv.line(R, (S_MAX-1, 0), (S_MAX-1, H_MAX-1), 255, 1)
hist_all = np.concatenate((hist_img, hist_roi, R), axis=1)
cv.imshow('hist img, roi, I/M', hist_all)

# B[x, y] = R[h(x, y), s(x, y)]
h, s, _ = cv.split(img_hsv)
B = R_rate[h, s]
B = np.minimum(B, 1.)
B *= 255.
B = B.astype(np.uint8)
B_bgr = cv.cvtColor(B, cv.COLOR_GRAY2BGR)

# blur mask
filter = cv.getStructuringElement(cv.MORPH_ELLIPSE, (5, 5))
B_filtered = cv.filter2D(B, -1, filter)
B_filtered_bgr = cv.cvtColor(B_filtered, cv.COLOR_GRAY2BGR)
ret, mask = cv.threshold(B_filtered, 50, 255, cv.THRESH_BINARY)
masked = cv.bitwise_and(img, img, mask=mask)

cv.rectangle(img, (10, 220), (10+W_ROI, 220+H_ROI), (0, 0, 255), 2)
img_row1 = np.concatenate((img, B_bgr), axis=1)
img_row2 = np.concatenate((B_filtered_bgr, masked), axis=1)
img_all = np.concatenate((img_row1, img_row2), axis=0)
rate = 350 / H
img_all = cv.resize(img_all, None, fx=rate, fy=rate, interpolation=cv.INTER_CUBIC)
cv.imshow('ori, roi, res', img_all)
